const fs = require("fs");
const path = require("path");
const marked = require("marked");
const { sendMarkdownFile } = require("./markdown_tool");

module.exports = function (app, api_prefix = "/api/markdown", folder) {
    const log4js = require('log4js');
    log4js.getLogger().debug(`Startup markdown api_prefix=${api_prefix} folder=${folder}`);
    // cgi, common gateway interface 通用网关接口
    // api, application programming  interface 应用程序接口
    function httpHandler(req, res, next) {
        res.writeHead(200, {
            'Content-Type': 'text/html; charset=utf-8',
        });
        let filename = req.params.file || "index.md";
        let mdfile = path.join(folder, filename);
        let exist = false;
        try {
            if (fs.lstatSync(mdfile).isFile()) {
                exist = true;
            }
        } catch (error) {

        }
        if (!exist) {
            res.status(404);
            res.end(
                `markdown file "${req.params.file}" not found`
            );
            return;
        }
        sendMarkdownFile(mdfile, res);
    }
    app.use(`${api_prefix}/:file`, httpHandler);
    app.use(`${api_prefix}/`, httpHandler);
}